package com.sca.bussiness.service.impl;

import com.sca.bussiness.service.LockService;
import com.sca.bussiness.utils.ZKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author liuxianfei
 * @since 2020/11/23 11:04
 */
@Slf4j
@Service
public class LockServiceImpl implements LockService {

    private final RedisTemplate<String, Object> redisTemplate;
    private int num = 0;

    public LockServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Boolean zookeeperLock() {
        boolean acquire = false;
        try {
            // acquire如果未获取到锁，会进行等待
            acquire = ZKUtil.acquire(180, TimeUnit.SECONDS);
            if (acquire) {
                num = num + 1;
                log.debug("当前num ：{}", num);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (acquire) {
                ZKUtil.release();
            }
        }
        return false;
    }

    @Override
    public Boolean redisLock() {
        Boolean lock = false;
        String key = "REDIS_LOCK";
        try {
            lock = redisTemplate.opsForValue().setIfAbsent(key, 1, 120, TimeUnit.SECONDS);
            if (lock) {
                num = num + 1;
                log.debug("当前num ：{}", num);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (lock) {
                redisTemplate.delete(key);
            }
        }
        return false;
    }
}
